﻿using System.Text.Json;
using Dark_Core_Server.Models.Article;
using Dark_Core_Server.Models.Universal;
using Dark_Core_Server.Models.User;
using Dark_Core_Server.Service;
using DarkSKL_Core.ArgModules;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;

namespace Dark_Core_Server.Controllers
{
    [Route("CoreService/[controller]:[action]")]
    [ApiController]
    public class ArticleController : ControllerBase
    {
        private readonly ArticleService ArticleService;
        private readonly UserService UserService;

        public ArticleController(ArticleService articleService, UserService userService)
        {
            this.ArticleService = articleService;
            this.UserService = userService;
        }

        #region 文章相关接口

        [HttpPost]
        [Authorize]
        public async Task<ActionResult> Create(SimpleArticleRecord record)
        {
            ResponseMsg<UserDocument> userResponseMsg = await UserService.ParseHttpRequestToUser(
                HttpContext.Request
            );
            if (userResponseMsg.Status != UniversalState.Success)
                return Ok(false.CreateResponseMsg("User not found", UniversalState.Error));

            return Ok(await ArticleService.CreateArticle(userResponseMsg.Data.id, record));
        }

        [HttpPost]
        public async Task<ActionResult> QueryList(PostRequestArgs args)
        {
            args.args.TryGetValue("payload", out var payload);
            if (payload == null)
                return Ok(
                    "No payload found in request.".CreateResponseMsg(
                        "缺少负载payload",
                        UniversalState.Error
                    )
                );

            args.args.TryGetValue("secondlyPayload", out var secondlyPayload);
            if (args.mode.ToArticleQueryMode() == ArticleQueryMode.AuthorIdAndFuzzyTitle ||
                args.mode.ToArticleQueryMode() == ArticleQueryMode.AuthorIdAndTag)
                if (secondlyPayload == null)
                    return Ok("缺少secondlyPayload参数".CreateResponseMsg("该参数为必填参数",UniversalState.Error));

            args.args.TryGetValue("isSortByTime", out var isSortByTime);
            if (isSortByTime == null)
            {
                return Ok("缺少isSortByTime参数".CreateResponseMsg("该参数为必填参数", UniversalState.Error));
            }

            bool sortByTime = false;


            if (isSortByTime is JsonElement je)
            {
                switch (je.ValueKind)
                {
                    case JsonValueKind.True:
                        sortByTime = true;
                        break;
                    case JsonValueKind.False:
                        sortByTime = false;
                        break;
                    case JsonValueKind.String:
                        // 前端有可能传的是字符串 "true" / "false"
                        bool.TryParse(je.GetString(), out sortByTime);
                        break;
                    // 如有需要，可根据实际情况处理 Number 或其他类型
                }
            }
            else
            {
                // 如果不是JsonElement，你再根据实际需求做处理
                // 例如尝试直接 .ToString() 然后 bool.TryParse(...)
                bool.TryParse(isSortByTime.ToString(), out sortByTime);
            }



            args.args.TryGetValue("pageNum", out var pageNum);
            args.args.TryGetValue("pageSize", out var pageSize);


            // 解析分页参数，转换成 int
            int pageNumVal = 0,
                pageSizeVal = 999;
            if (pageNum != null)
                int.TryParse(pageNum.ToString(), out pageNumVal);
            if (pageSize != null)
                int.TryParse(pageSize.ToString(), out pageSizeVal);
            if (pageSizeVal == 0)
                pageSizeVal = 999;
            return Ok(
                await ArticleService.QueryArticleListAsync(
                    args.mode.ToArticleQueryMode(),
                    new string[]{payload?.ToString() ?? String.Empty,secondlyPayload?.ToString() ?? String.Empty},
                    sortByTime,
                    pageNumVal,
                    pageSizeVal
                )
            );
        }

        [HttpPost]
        public async Task<ActionResult> QueryDetail(PostRequestArgs args)
        {
            args.args.TryGetValue("payload", out var payload);
            if (payload == null)
                return Ok(
                    "No payload found in request.".CreateResponseMsg(
                        "缺少负载payload",
                        UniversalState.Error
                    )
                );
            return Ok(await ArticleService.QueryArticleContentAsync(payload.ToString()??String.Empty));
        }

        [HttpPost]
        [Authorize]
        public async Task<ActionResult> Delete(PostRequestArgs args)
        {
            ResponseMsg<UserDocument> userResponseMsg = await UserService.ParseHttpRequestToUser(
                HttpContext.Request
            );
            if (userResponseMsg.Status != UniversalState.Success)
                return Ok(false.CreateResponseMsg("User not found", UniversalState.Error));

            args.args.TryGetValue("payload", out var payload);
            if (payload == null)
                return Ok(
                    "No payload found in request.".CreateResponseMsg(
                        "缺少负载payload",
                        UniversalState.Error
                    )
                );

            if (!ObjectId.TryParse(payload.ToString(), out var payloadId))
                return Ok(false.CreateResponseMsg("Invalid ObjectId", UniversalState.Error));

            return Ok(await ArticleService.DeleteArticleAsync(userResponseMsg.Data.id, payloadId));
        }

        [HttpPost]
        [Authorize]
        public async Task<ActionResult> Modify(PostRequestArgs args)
        {
            ResponseMsg<UserDocument> userResponseMsg = await UserService.ParseHttpRequestToUser(
                HttpContext.Request
            );
            if (userResponseMsg.Status != UniversalState.Success)
                return Ok(false.CreateResponseMsg("User not found", UniversalState.Error));

            args.args.TryGetValue("payload", out var payload);
            if (payload == null)
                return Ok(
                    "No payload found in request.".CreateResponseMsg(
                        "缺少负载payload",
                        UniversalState.Error
                    )
                );

            if (!ObjectId.TryParse(payload.ToString(), out var payloadId))
                return Ok(false.CreateResponseMsg("Invalid ObjectId", UniversalState.Error));

            // 解析其他参数
            args.args.TryGetValue("title", out var title);
            args.args.TryGetValue("content", out var content);
            args.args.TryGetValue("tags", out var tags);
            args.args.TryGetValue("Synopsis", out var synopsis);
            args.args.TryGetValue("pictureUrl", out var pictureUrl);
            args.args.TryGetValue("viewLevel", out var viewLevel);
            args.args.TryGetValue("fileIds", out var fileIds);

            string[]? tagsArray = null;
            string[]? fileIdsArray = null;

            // 解析 tags 数组
            if (tags is not null)
            {
                if (((JsonElement)tags).ValueKind != JsonValueKind.Array)
                    return Ok(false.CreateResponseMsg("Invalid tags format", UniversalState.Error));

                tagsArray = ((JsonElement)tags)
                    .EnumerateArray()
                    .Select(t => t.ToString())
                    .ToArray();
            }

            // 解析 fileIds 数组
            if (fileIds is not null)
            {
                if (((JsonElement)fileIds).ValueKind != JsonValueKind.Array)
                    return Ok(
                        false.CreateResponseMsg("Invalid fileIds format", UniversalState.Error)
                    );

                fileIdsArray = ((JsonElement)fileIds)
                    .EnumerateArray()
                    .Select(t => t.ToString())
                    .ToArray();
            }

            ModifyArticleRecord record =
                new(
                    title == null ? null : title.ToString(),
                    content == null ? null : content.ToString(),
                    synopsis == null?null: synopsis.ToString(),
                    pictureUrl == null ? null : pictureUrl.ToString(),
                    viewLevel == null ? default : Convert.ToInt32(viewLevel),
                    tagsArray,
                    fileIdsArray
                );

            return Ok(
                await ArticleService.UpdateArticleAsync(userResponseMsg.Data.id, payloadId, record)
            );
        }

        #endregion

        #region 评论相关接口 (集成在 ArticleService 中)

        /// <summary>
        /// 创建评论
        /// </summary>
        [HttpPost]
        [Authorize]
        public async Task<ActionResult> CreateComment(PostRequestArgs args)
        {
            // 解析当前用户
            ResponseMsg<UserDocument> userResponseMsg = await UserService.ParseHttpRequestToUser(
                HttpContext.Request
            );
            if (userResponseMsg.Status != UniversalState.Success)
                return Ok(false.CreateResponseMsg("User not found", UniversalState.Error));

            // 解析评论参数
            args.args.TryGetValue("articleId", out var articleIdObj);
            args.args.TryGetValue("content", out var contentObj);

            if (articleIdObj == null || contentObj == null)
                return Ok(
                    false.CreateResponseMsg("缺少参数 articleId 或 content", UniversalState.Error)
                );

            if (!ObjectId.TryParse(articleIdObj.ToString(), out var articleId))
                return Ok(false.CreateResponseMsg("Invalid articleId", UniversalState.Error));

            string content = contentObj.ToString() ?? string.Empty;
            if (string.IsNullOrWhiteSpace(content))
                return Ok(false.CreateResponseMsg("评论内容不能为空", UniversalState.Error));

            // 调用服务
            var result = await ArticleService.CreateCommentAsync(
                userResponseMsg.Data.id,
                articleId,
                content
            );

            return Ok(result);
        }

        /// <summary>
        /// 查询评论
        /// </summary>
        [HttpPost]
        public async Task<ActionResult> QueryComment(PostRequestArgs args)
        {
            var queryMode = args.mode .ToString().ToUpper() switch
            {
                "COMMENTID" => CommentQueryMode.CommentID,
                "ARTICLEID" => CommentQueryMode.ArticleID,
                "USERID" => CommentQueryMode.UserID,
                _ => CommentQueryMode.ArticleID
            };


            // 解析其他参数
            args.args.TryGetValue("payload", out var payload);
            args.args.TryGetValue("pageNum", out var pageNum);
            args.args.TryGetValue("pageSize", out var pageSize);

            // 调用服务
            var result = await ArticleService.QueryCommentAsync(
                queryMode,
                payload?.ToString() ?? string.Empty,
                pageNum is null ? 0 : Convert.ToInt32(pageNum),
                pageSize is null || Convert.ToInt32(pageSize) == 0 ? 999 : Convert.ToInt32(pageSize)
            );

            return Ok(result);
        }

        /// <summary>
        /// 更新评论
        /// </summary>
        [HttpPost]
        [Authorize]
        public async Task<ActionResult> UpdateComment(PostRequestArgs args)
        {
            // 解析当前用户
            ResponseMsg<UserDocument> userResponseMsg = await UserService.ParseHttpRequestToUser(
                HttpContext.Request
            );
            if (userResponseMsg.Status != UniversalState.Success)
                return Ok(false.CreateResponseMsg("User not found", UniversalState.Error));

            // 解析评论ID / 新内容
            args.args.TryGetValue("payload", out var commentIdObj);
            args.args.TryGetValue("content", out var newContentObj);

            if (commentIdObj == null || newContentObj == null)
                return Ok(
                    false.CreateResponseMsg(
                        "缺少参数 payload(评论ID) 或 content(新内容)",
                        UniversalState.Error
                    )
                );

            if (!ObjectId.TryParse(commentIdObj.ToString(), out var commentId))
                return Ok(false.CreateResponseMsg("Invalid commentId", UniversalState.Error));

            var newContent = newContentObj.ToString() ?? string.Empty;
            if (string.IsNullOrWhiteSpace(newContent))
                return Ok(false.CreateResponseMsg("评论内容不能为空", UniversalState.Error));

            // 调用服务
            var result = await ArticleService.UpdateCommentAsync(
                commentId,
                userResponseMsg.Data.id,
                newContent
            );

            return Ok(result);
        }

        /// <summary>
        /// 删除评论
        /// </summary>
        [HttpPost]
        [Authorize]
        public async Task<ActionResult> DeleteComment(PostRequestArgs args)
        {
            // 解析当前用户
            ResponseMsg<UserDocument> userResponseMsg = await UserService.ParseHttpRequestToUser(
                HttpContext.Request
            );
            if (userResponseMsg.Status != UniversalState.Success)
                return Ok(false.CreateResponseMsg("User not found", UniversalState.Error));

            // 解析评论ID
            args.args.TryGetValue("payload", out var commentIdObj);
            if (commentIdObj == null)
                return Ok(false.CreateResponseMsg("缺少参数 payload(评论ID)", UniversalState.Error));

            if (!ObjectId.TryParse(commentIdObj.ToString(), out var commentId))
                return Ok(false.CreateResponseMsg("Invalid commentId", UniversalState.Error));

            // 调用服务
            var result = await ArticleService.DeleteCommentAsync(
                commentId,
                userResponseMsg.Data.id
            );

            return Ok(result);
        }

        #endregion
    }
}
